package com.ywj.chatroom.multiroom.server;

import com.ywj.chatroom.multiroom.protocol.MessageCodecSharable;
import com.ywj.chatroom.multiroom.protocol.ProcotolFrameDecoder;
import com.ywj.chatroom.multiroom.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        ChatRequestHandler CHAT_HANDLER = new ChatRequestHandler();
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        GroupMembersRequestMessageHandler GROUP_MEMBERT_HANDLER = new GroupMembersRequestMessageHandler();
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        GroupChatRequestMessageHandler CROUP_CHAR_HANDLER = new GroupChatRequestMessageHandler();
        QuitHandler QUIT_HANDLER = new QuitHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>(){
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //空闲状态检测器：心跳检测，假死的连接占用的资源不能自动释放
                    //用来判断是不是读空闲时间过程或者写空闲时间过长
                    // 参数1：读    参数2：写   参数3：读写
                    // 5秒内如果没有收到channel读入的数据，就会触发一个事件 IdleState.READER_IDLE
                    ch.pipeline().addLast(new IdleStateHandler(5, 8, 0));
                    //心跳检测的处理器 ChannelDuplexHandler可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler(){
                        //用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            IdleStateEvent event = (IdleStateEvent) evt;
                            if(event.state() == IdleState.READER_IDLE){
                                //触发了读空闲事件
                                //log.debug("已经5秒了没有读到数据了");
                                ctx.channel().close();
                            }
                        }
                    });

                    //ProcotolFrameDecoder() 提取出来作为一个单独的类，channel独有的，不能共享
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                    //ch.pipeline().addLast(LOGGING_HANDLER);
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //我们用SimpleChannelInboundHandler对指定消息做操作
                    //登录处理器
                    ch.pipeline().addLast((ChannelHandler) LOGIN_HANDLER);
                    //好友聊天消息处理器
                    ch.pipeline().addLast(CHAT_HANDLER);
                    //群聊创建处理器
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                    //加入群聊处理器
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                    //群成员处理器
                    ch.pipeline().addLast(GROUP_MEMBERT_HANDLER);
                    //退出群聊处理器
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                    //群聊天处理器
                    ch.pipeline().addLast(CROUP_CHAR_HANDLER);
                    //正常异常退出客户端
                    ch.pipeline().addLast(QUIT_HANDLER);

                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e){
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
